/**
 * Author: w景洋.
 * Time: 2016/7/6 0006
 */
angular.module('module.coupon')
    .controller('ReceiveCouponController', ReceiveCouponController);

// 领取优惠券
ReceiveCouponController.$inject = ['$state', '$localStorage', 'CouponService'];
function ReceiveCouponController($state, $localStorage, CouponService) {
    var $storage = $localStorage.$default({
        recommend: []
    });
    var vm = this;
    vm.couponList = [];
    vm.recShop = [];
    vm.receive = receive;
    
    var userid = getCookie("_userId");
    activate();

    //////

    function activate() {
        if ($storage.recommend.length >= 0) {
            vm.recShop = $storage.recommend;
            prepare_shopname(vm.recShop, 0);
        }
        function prepare_shopname(list, i) {
            if (i >= list.length) {
                CouponService.getByReceiverId(userid).$promise.then(function (List) {
                    for (var k = 0; k < vm.couponList.length; k++) {
                        for (var g = 0; g < List.length; g++) {
                            if (List[g].couponid == vm.couponList[k].couponid) {
                                vm.couponList[k].receive = true;
                            }
                        }
                    }
                });
                return;
            }
            var item = list[i];
            CouponService.getByshopid(item.shopid).$promise.then(function (data) {
                var coupon = data;
                for (var j = coupon.length - 1; j >= 0; j--) {
                    coupon[j].shopname = item.name;
                    if (coupon[j].num == 0) {
                        coupon.splice(j, 1);
                    }
                    else {
                        vm.couponList.push(coupon[j]);
                    }
                }
                prepare_shopname(list, i + 1);
            }, function () {
                prepare_shopname(list, i + 1);
            });
        };
    }

    function receive(coupon) {
        if (userid == null) {
            alert("请先登录");
            var backurl = window.location.href;
            $state.go("login", {backurl:backurl});
        } else {
            var reciver = {
                "couponid": coupon.couponid,
                "receiverid": userid,
                "status": 0,
            };
            CouponService.saveBycouponid(reciver, function (data) {
                input_alert("领取成功");
                coupon.num--;
                coupon.receive = true;
            }, function (data) {
                input_alert("领取失败，请重新登录");
            })
        }
    }
}